#This code fetches image art from amazon. But TBH amazon API is overkil for this.
#Discogs has better images so let's use that.
#This is mothballed.

from stages import GlobalStage
from config import Config
import os
from mutagen.flac import FLAC
import urllib2
import urllib
import xml.etree.ElementTree as ET
import gzip
import StringIO

def fetchImageUri(key):
    url = "http://www.discogs.com/release/%s?f=xml&api_key=%s" % (key, Config[ "discogsid" ] )
    print( "url is: %s\n" % url )
    request = urllib2.Request( url )
    #seems like discogs will gzip no matter what we do. how annoying
    #request.add_header( "Accept-Encoding", "identity" )
    response = urllib2.urlopen(request)
    content = response.read()
    data = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(content))
    tree = ET.parse( data )
    root = tree.getroot()
    #possibly heavy-handed, since it's really resp/release/images/image, but hey why not?
    images = root.getiterator( tag="image" )
    uri = None
    for imagenode in images:
        attribs = imagenode.attrib
        if( attribs["type"] == "primary" or uri == None ):
            uri = attribs[ "uri" ]
            return( uri )
    return( uri )

class FetchCoverArt(GlobalStage):
    file = "cover.jpg"
        
    def __init__(self, shagger):
        GlobalStage.__init__(self, shagger) 
    
    def preamble(self):
        return "Fetch cover art"
    
    def canWork(self):
        files = self.shagger.fileSubset("")
        for file in files:
            if file.endswith(self.file):
                return False
        return True
    
    def work(self):
        files = self.shagger.fileSubset("flac")
        audio = FLAC( files[0] )
        if not audio.has_key("DISCOGS"):
            self.shagger.log("No discogs found so can't fetch cover art")
            return True
        discogsurl = audio["DISCOGS"][0]        
        key = discogsurl.split("/")[-1]
        uri = fetchImageUri( key )
        f = self.filename(self.file)
        urllib.urlretrieve(uri, f)            
        return True


